package com.ergou.easylive.admin.controller.auth;

import com.ergou.easylive.admin.annotation.AccessLog;
import com.ergou.easylive.admin.entity.dto.SysLoginDTO;
import com.ergou.easylive.admin.entity.po.SysUser;
import com.ergou.easylive.admin.entity.vo.LoginVO;
import com.ergou.easylive.admin.properties.JwtProperties;
import com.ergou.easylive.admin.service.SysUserService;
import com.ergou.easylive.common.entity.response.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 后台登录 Controller
 *
 * @author Er-Gou
 * @date 2025-09-16 21:14
 */
@RestController
@RequestMapping("/auth")
@Slf4j
@Tag(name = "用户认证", description = "用户登录、注册、权限验证等认证相关接口")
@Validated
public class SysLoginController {

    @Resource
    private SysUserService sysUserService;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户名密码登录，返回JWT Token")
    @AccessLog(value = "用户登录")
    public Result<LoginVO> doLogin(@Valid @RequestBody SysLoginDTO sysLoginDTO) {
        try {
            log.info("用户登录请求：username={}", sysLoginDTO.getUsername());

            // 调用登录服务
            String token = sysUserService.login(sysLoginDTO);

            // 获取用户信息
            SysUser user = sysUserService.getUserByUsername(sysLoginDTO.getUsername());
            user.setPassword(null);
            // 构造返回结果
            LoginVO loginVO = new LoginVO()
                    .setToken(token).setUserInfo(user);

            log.info("用户登录成功：username={}", sysLoginDTO.getUsername());

            return Result.success(loginVO);
        } catch (Exception e) {
            log.error("用户登录失败：username={}, error={}", sysLoginDTO.getUsername(), e.getMessage());
            return Result.fail(400, e.getMessage());
        }
    }

}
